package active

import (
	"server/game/cache"
	"server/game/model"

	"github.com/hwcer/cosgo/registry"
	"github.com/hwcer/yyds/context"
	"github.com/hwcer/yyds/errors"
)

const (
	supmailSubmit uint8 = 1
	supmailDelete uint8 = 2
)

type ConfigAType int8

const (
	ConfigATypeMail ConfigAType = 2
	ConfigATypeCode ConfigAType = 101
)

type ConfigStatus int8

func init() {
	Register(&Supmail{})
}

// Supmail 全服邮件
type Supmail struct {
	Id    uint32      `json:"id" bson:"_id"`
	AType ConfigAType `json:"AType" bson:"AType"`
	//Ignore int64       `json:"ignore"`
	Attach string  `json:"attach"`
	Expire []int64 `json:"expire"`
}

func (this *Supmail) Caller(node *registry.Node, handle *context.Context) interface{} {
	f := node.Method().(func(*Supmail, *context.Context) interface{})
	return f(this, handle)
}

// Submit 标记为已读并领取邮件道具(如果有)
//
// id int 配置ID
//
// del int 看完直接删除
//
// /active/supmail/submit
func (this *Supmail) Submit(c *context.Context) interface{} {
	id := c.GetInt32("id")
	if id == 0 {
		return c.Error("id empty")
	}
	mod := &Config{Id: uint32(id)}
	err := mod.Init()
	if err != nil {
		return err
	}
	if mod.AType != ConfigATypeMail {
		return c.Error("not Supmail")
	}

	var limits [2]int64
	if limits, err = mod.Verify(c.Player); err != nil {
		return err
	}
	handle := cache.GetActive(c.Player.Updater)
	handle.Select(id)

	c.Player.AddWithString(mod.Attach, ",")
	if err = c.Player.Data(); err != nil {
		return err
	}
	var item *model.Active
	if item, err = handle.GetOrCreate(id, limits[1]); err != nil {
		return err
	}
	data := uint8(0)
	if err = item.Unmarshal(&data); err != nil {
		return err
	}
	if data > 0 {
		return errors.ErrDataExists
	}
	data = supmailSubmit
	if del := c.GetInt32("del"); del > 0 {
		data = supmailDelete
	}
	handle.SetAttach(item.OID, data)
	return true
}

// Delete 删除超级邮件
//
// id int 配置ID
//
// path: /active/supmail/delete
func (this *Supmail) Delete(c *context.Context) interface{} {
	id := c.GetInt32("id")
	if id == 0 {
		return c.Error("id empty")
	}
	handle := cache.GetActive(c.Player.Updater)
	handle.Select(id)
	if err := c.Player.Data(); err != nil {
		return err
	}
	item := handle.Get(id)
	if item == nil {
		return c.Error("还没领取附件，不可以删除")
	}
	data := uint8(0)
	if err := item.Unmarshal(&data); err != nil {
		return err
	}
	if data != supmailDelete {
		data = supmailDelete
		handle.SetAttach(item.OID, data)
	}
	return true
}
